﻿using NLog;
using SqlSugar;
using Microsoft.Extensions.Configuration;

namespace MqttToDatabase
{
    class Program
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        static async Task Main(string[] args)
        {

            // 读取配置文件
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

            // 初始化日志
            LogManager.Setup().LoadConfigurationFromFile("NLog.config");
            string logDirectory = configuration["Logging:LogPath"];
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            // 获取数据库连接字符串
            string connectionString = configuration.GetSection("ConnectionStrings")["Default"];

            //初始化sqlsugar
            var sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            });
            // 获取 MQTT 配置
            var mqttSettings = configuration.GetSection("MqttSettings");
            string server = mqttSettings["Server"];
            int port = int.Parse(mqttSettings["Port"]);
            string clientId = mqttSettings["ClientId"];
            string username = mqttSettings["Username"];
            string password = mqttSettings["Password"];

            // 创建 DatabaseService 并传入 SqlSugar 实例
            var databaseService = new DatabaseService(sqlSugar);
            MqttClientService service = new MqttClientService(databaseService);

            // 异步连接到 MQTT 服务器
            await service.ConnectAsync(server, port, clientId, username, password);

            string input;
            do
            {
                input = Console.ReadLine()?.Trim();
            } while (input?.ToLower() != "exit");

            Console.WriteLine("正在关闭服务...");
            Logger.Info("用户请求退出");

            // 断开与 MQTT 服务器的连接
            await service.DisconnectAsync();
            Logger.Info("应用程序结束");
        }
    }
}